﻿/**
 * Created by Administrator on 2017/8/18 0018.
 */
var express = require('express');
var crypto = require("crypto");
var qr = require('qr-image')
var multer = require("multer");
var config = require('../../config.js');
var db = require('../../db/db.js');
var log = require("../../util/logger");
var moment = require("moment");
var path = require("path");
var fs = require("fs");
var router = express.Router();

var manage_model = require('../../model/manage.js');
var person_model = require('../../model/person');
var order_model = require("../../model/orders");
var jiaose_model = require("../../model/system_jiaose");
var orders_model = require("../../model/orders");

var sms = require("../../util/sms");
var myutil = require("../../util/util");
var wx_applets = require("../../util/wx_applets");




router.post('/list', async function (req, res) {
    var page;
    var rows;
    if (isNaN(req.body.page)) {
        page = 1;
    } else {
        page = +req.body.page;
    }
    if (isNaN(req.body.rows)) {
        rows = 10;
    } else {
        rows = +req.body.rows;
    }
    var first = rows * (page - 1);

    var where = " 1=1 ";

    if (typeof (req.body.truename) != "undefined" && req.body.truename != "") {
        where = where + " and truename like  '%" + req.body.truename + "%'";

    }
    if (typeof (req.body.phone) != "undefined" && req.body.phone != "") {
        where = where + " and phone like  '%" + req.body.phone + "%'";

    }
    if (req.body.stime != undefined && req.body.stime != "" && req.body.etime != undefined && req.body.etime != "") {
        where += " and createtime between '" + req.body.stime + "' and '" + req.body.etime + " 23:59:59' ";
    }


    console.log("where", where);
    var list = await person_model.getlist(rows, first, where, "", "order by (SELECT count(*) from orders where orders.personid=person.id)+person.znum desc");
    for (var i = 0; i < list.length; i++) {

        list[i].createtime = moment(list[i].createtime).format("YYYY-MM-DD HH:mm:ss");

        var ordernum = await order_model.getcount("personid=" + list[i].id);
        list[i].num = ordernum + parseInt(list[i].znum);

    }
    var count = await person_model.getcount(where);
    var allcount = parseInt(parseInt(count) / rows) + 1;
    if (count % rows == 0) {
        allcount = allcount - 1;
    }

    res.send({ status: 200, data: list, message: "", allcount: allcount, count: count });

});



router.delete('/del', async function (req, res) {

    var where = " id=" + req.body.id;
    var obj = await person_model.del(where);
    if (obj.code == 200) {
        var result = {
            "status": "200",
            "message": "success"
        }
        res.jsonp(result);
    } else {
        var result = {
            "status": "400",
            "message": "success"
        }
        res.jsonp(result);
    }


});



router.post('/edit', async function (req, res) {

    var obj = await person_model.edit(req.body);
    if (obj.code == 200) {
        var result = {
            "status": "200",
            "message": "success"
        }
        res.jsonp(result);
    } else {
        var result = {
            "status": "400",
            "message": "success"
        }
        res.jsonp(result);
    }


});




router.post('/add', async function (req, res) {

    var data = req.body;


    data.createtime = new Date();
    var obj = await person_model.add(data);
    if (obj.code == 200) {


        var result = {
            "status": "200",
            "message": "操作成功"
        }
        res.jsonp(result);
    } else {
        var result = {
            "status": "400",
            "message": "success"
        }
        res.jsonp(result);
    }


});





async function sendmessage(open_id, message, page) {


    var token = await wx_applets.gettoken();

    var obj = {};
    obj.openid = open_id;
    obj.template_id = "5bJAe6LAh8jQZ1N4Jx0lv7eKfqZOCm6zj_FiRR2VUSg";
    var json = {};
    json.phrase1 = {
        value: message.phrase1
    }
    json.phrase3 = {
        value: message.phrase3
    }


    var result = await wx_applets.sendTemplateMessage(obj, token.access_token, json, page);
    console.log("result", result);
}

router.post('/sh', async function (req, res) {









    var obj = await db.execute("update person set state=1 where id=" + req.body.id);
    if (obj.code == 200) {


        var user = await db.query("select users.*,person.id as personid from users join person on person.userid=users.id where person.id=" + req.body.id);
        if (user.length > 0) {
            var open_id = user[0].open_id;
            var page = "pages/goods/index?id=" + user[0].personid;
            var json = {};
            json.phrase1 = "通过";
            json.phrase3 = "个人认证";
            sendmessage(open_id, json, page);

        }


        var result = {
            "status": "200",
            "message": "操作成功",
            data: ""
        }
        res.jsonp(result);
    } else {
        var result = {
            "status": "400",
            "message": "err",
        }
        res.jsonp(result);
    }




});


router.post('/pushdata', async function (req, res) {

    var user = await db.query("select person.*,users.open_id from users join person on person.userid=users.id where person.id=" + req.body.id);
    if (user.length > 0) {
        var open_id = user[0].open_id;
        var page = "";
        var json = {};
        json.phrase1 = "通过";
        json.phrase3 = "个人认证";

        var file = path.join(__dirname, '../../config/config.json');
        var myconfig = {};
        if (fs.existsSync(file)) {
            var ss = fs.readFileSync(file);
            var str = {};
            if (ss != "") {
                myconfig = JSON.parse(ss);
            }
        }


        var token = await wx_applets.gettoken();

        var num = user[0].znum + user[0].mynum + await orders_model.getcount("personid=" + user[0].id);


        var obj = {};
        obj.openid = open_id;
        obj.template_id = "DvPA2GZD9UYfw_yH2F9EhhbsXb6inWCjr_tNZhx7_hI";
        var json = {};
        json.thing1 = {
            value: "当前票数" + num + "张"
        }
        json.thing3 = {
            value: myconfig.push_guize
        }
        json.thing4 = {
            value: myconfig.push_jiangxiang
        }
        json.time2 = {
            value: myconfig.push_endtime
        }
        var page = "pages/goods/index?id=" + user[0].id;

        var ss = await wx_applets.sendTemplateMessage(obj, token.access_token, json, page);

        var result = {
            "status": "200",
            "message": "操作成功",
            data: ""
        }
        res.jsonp(result);
    } else {
        var result = {
            "status": "400",
            "message": "系统错误",
            data: ""
        }
        res.jsonp(result);
    }



});



router.post('/tixian/list', async function (req, res) {
    var page;
    var rows;
    if (isNaN(req.body.page)) {
        page = 1;
    } else {
        page = +req.body.page;
    }
    if (isNaN(req.body.rows)) {
        rows = 10;
    } else {
        rows = +req.body.rows;
    }
    var first = rows * (page - 1);

    var where = " 1=1 ";
    if (typeof (req.body.wxapp_id) != "undefined" && req.body.wxapp_id != "") {
        where = where + " and wxapp_id=" + req.body.wxapp_id;

    }
    if (typeof (req.body.goodname) != "undefined" && req.body.goodname != "") {
        where = where + " and goodname like '%" + req.body.goodname + "%'";

    }


    if (typeof (req.body.stime) != "undefined" && typeof (req.body.etime) != "undefined" && req.body.stime != "" && req.body.etime != "") {
        where = where + " and createtime between '" + req.body.stime + "' and '" + req.body.etime + " 23:59:59'";

    }



    console.log("where", where);
    var list = await tixian_model.getlist(rows, first, where, " join apply on apply.userid = tixian.mid ", " order by tixian.createtime ", " tixian.*,apply.sitename ");
    for (var i = 0; i < list.length; i++) {

        list[i].createtime = moment(list[i].createtime).format("YYYY-MM-DD HH:mm:ss");


        if (list[i].shenhetime != null && list[i].shenhetime != "") {
            list[i].shenhetime = moment(list[i].shenhetime).format("YYYY-MM-DD HH:mm:ss");
        }



    }
    var count = await tixian_model.getcount(where, " join apply on apply.userid = tixian.mid ");
    var allcount = parseInt(parseInt(count) / rows) + 1;
    if (count % rows == 0) {
        allcount = allcount - 1;
    }

    res.send({ status: 200, data: list, message: "", allcount: allcount, count: count });

});


router.post('/tixian/sh', async function (req, res) {

    var data = req.body;
    data.createtime = new Date();



    var obj = await db.execute("update tixian set  state=?,shenhetime=? where id=?", [1, new Date(), req.body.id]);

    if (obj.code == 200) {
        var result = {
            "status": "200",
            "message": "操作成功",
            data: ""
        }

        res.jsonp(result);
    } else {
        var result = {
            "status": "400",
            "message": "err",
            data: ""
        }
        res.jsonp(result);

    }




});




router.post('/updateimg', async function (req, res) {

    var data = req.body;
    data.createtime = new Date();

    var obj = await db.execute("update apply set  kefuimgurl=? where userid=?", [req.body.kefuimgurl, req.body.mid]);
    if (obj.code == 200) {
        var result = {
            "status": "200",
            "message": "操作成功",
            data: ""
        }

        res.jsonp(result);
    } else {
        var result = {
            "status": "400",
            "message": "err",
            data: ""
        }
        res.jsonp(result);

    }
});

router.post('/updategzhimg', async function (req, res) {

    var data = req.body;
    data.createtime = new Date();


    var obj = await db.execute("update apply set  gzhimgurl=? where userid=?", [req.body.kefuimgurl, req.body.mid]);
    if (obj.code == 200) {
        var result = {
            "status": "200",
            "message": "操作成功",
            data: ""
        }

        res.jsonp(result);
    } else {
        var result = {
            "status": "400",
            "message": "err",
            data: ""
        }
        res.jsonp(result);

    }
});






router.post('/apply/tj', async function (req, res) {

    var where = " 1=1 ";
    var where1 = "";

    if (typeof (req.body.name) != "undefined" && req.body.name != "") {
        where = where + " and sitename like  '%" + req.body.name + "%'";

    }

    if (typeof (req.body.stime) != "undefined" && typeof (req.body.etime) != "undefined" && req.body.stime != "" && req.body.etime != "") {
        where1 = " and create_time between '" + req.body.stime + "' and '" + req.body.etime + " 23:59:59'";

    }


    console.log("where", where);
    var list = await apply_model.getinfo(where);
    for (var i = 0; i < list.length; i++) {

        list[i].ordernum_day = await order_model.getcount("pay_status=1 and  to_days(create_time) = to_days(now()) and wxapp_id=" + list[i].userid);
        var obj2 = await db.query("select sum(total_price) as money from yoshop_order where pay_status=1 and  to_days(create_time) = to_days(now()) and  wxapp_id=" + list[i].userid, []);
        if (obj2.length > 0) {
            list[i].paymoney_day = parseInt(obj2[0].money);
        }

        list[i].ordernum = await order_model.getcount("pay_status=1 and wxapp_id=" + list[i].userid + where1);
        var obj3 = await db.query("select sum(total_price) as money from yoshop_order where pay_status=1 and  wxapp_id=" + list[i].userid + where1, []);
        if (obj3.length > 0) {
            list[i].paymoney = parseInt(obj3[0].money);
        }

    }


    res.send({ status: 200, data: list, message: "" });

});




router.get('/pushall', async function (req, res) {

    var user = await db.query("select person.*,users.open_id from users join person on person.userid=users.id ");
 
    var file = path.join(__dirname, '../../config/config.json');
    var myconfig = {};
    if (fs.existsSync(file)) {
        var ss = fs.readFileSync(file);
        if (ss != "") {
            myconfig = JSON.parse(ss);
        }
    }

    for (var i = 0; i < user.length; i++) {
        var token = await wx_applets.gettoken();

        var open_id = user[i].open_id;
        var page = "";
        var json = {};
        json.phrase1 = "通过";
        json.phrase3 = "个人认证";


        var num = user[i].znum + user[i].mynum + await orders_model.getcount("personid=" + user[i].id);
        var obj = {};
        obj.openid = open_id;
        obj.template_id = "DvPA2GZD9UYfw_yH2F9EhhbsXb6inWCjr_tNZhx7_hI";
        var json = {};
        json.thing1 = {
            value: "当前票数" + num + "张"
        }
        json.thing3 = {
            value: myconfig.push_guize
        }
        json.thing4 = {
            value: myconfig.push_jiangxiang
        }
        json.time2 = {
            value: myconfig.push_endtime
        }
        var page = "pages/goods/index?id=" + user[i].id;

        var ss = await wx_applets.sendTemplateMessage(obj, token.access_token, json, page);


        

    }


    res.send("推送成功");


});

module.exports = router;   /*暴露这个 router模块*/